package cn.edu.xmu.oomall.coupon.mq;

import cn.edu.xmu.oomall.coupon.mapper.CouponActivityPoMapper;
import cn.edu.xmu.oomall.coupon.model.bo.CouponActivity;
import cn.edu.xmu.oomall.coupon.model.po.CouponActivityPo;
import io.swagger.models.auth.In;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author Yujie Lin
 * @date 2021/12/27 21:52
 */
@Service
@Lazy
@RocketMQMessageListener(topic = "customer-coupon-topic",  consumeMode = ConsumeMode.CONCURRENTLY, consumeThreadMax = 10, consumerGroup = "customer-coupon-group")
public class CouponListener implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {


    private static final Logger logger = LoggerFactory.getLogger(CouponListener.class);


    @Autowired
    private CouponActivityPoMapper couponActivityPoMapper;


    @Override
    public void onMessage(String s) {
        logger.info(LocalDateTime.now()+":优惠活动"+s+"收到消息，开始减库存");

        Long activityId=Long.valueOf(s);
        CouponActivityPo couponActivityPo=couponActivityPoMapper.selectByPrimaryKey(activityId);

        Integer quantity=couponActivityPo.getQuantity();

        couponActivityPo.setQuantity(quantity-1);
        couponActivityPoMapper.updateByPrimaryKey(couponActivityPo);
        logger.info(LocalDateTime.now()+":"+"优惠活动"+s+"扣库存完成");
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {

    }
}
